﻿using Mall.Application;
using Mall.Core;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;

namespace Mall.Web.Entry.Controllers
{
    public class AccountController : Controller
    {
        private readonly IUserService _userService;
        public AccountController(IUserService userService)
        {
            _userService = userService;
        }
        public IActionResult Login()
        {
            return View();
        }

        [HttpPost]
        public IActionResult Login(LoginDto loginDto)
        {
            var isLogin = _userService.CheckLogin(loginDto);
            if (isLogin)
            {
                var claims = new List<Claim>
                    {
                        new Claim(ClaimTypes.Name, loginDto.UserName)
                    };

                var claimsIdentity = new ClaimsIdentity(
                claims, CookieAuthenticationDefaults.AuthenticationScheme);

                HttpContext.SignInAsync(new ClaimsPrincipal(claimsIdentity),
                    new AuthenticationProperties
                    {
                        IsPersistent = true,             //持久化cookie
                        ExpiresUtc = DateTime.UtcNow.AddMinutes(20)  //cookie有效期20分钟
                    });
                return Json(new LoginResult { Code = "000", Msg = "登录成功", Url = "/home/index" });
            }
            return Json(new LoginResult { Code = "100", Msg = "用户名或密码错误" });
        }

        public IActionResult Logout()
        {
            HttpContext.SignOutAsync();
            return RedirectToAction("Login");
        }
    }
}
